package com.base.mybaseproject.base;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.ProgressDialog;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;

import com.support.Utils;

public class BaseAsyncTask extends AsyncTask<Object, Object, JSONObject> {
	Context context;
	ProgressDialog pb = null;

	protected BaseAsyncTask(Context context) {
		this.context = context;

	}

	@Override
	protected void onPreExecute() {
		// 3G
		// Data
		// mobile
		// Network
		boolean connect = false;
		ConnectivityManager conMan = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

		NetworkInfo wifi = conMan.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

		if (conMan != null) {
			android.net.NetworkInfo[] infos = conMan.getAllNetworkInfo();
			if (infos != null) {
				for (int i = 0; i < infos.length; i++) {
					if (infos[i].getState() == android.net.NetworkInfo.State.CONNECTED
							|| infos[i].getState() == android.net.NetworkInfo.State.CONNECTING
							|| wifi.isConnected() == true) {
						connect = true;
					}
				}
			}
		}
		if (!connect) {
			Utils.showToast(context, "请检查网络");
			this.cancel(true);
		} else {
			if (pb == null) {
				pb = new ProgressDialog(context);
				pb.setCancelable(false);
				pb.setCanceledOnTouchOutside(false);
				pb.setMessage("Loading...");
			} else {

			}
			if (pb.isShowing()) {

			} else {
				pb.show();
			}
		}
	}

	@Override
	protected JSONObject doInBackground(Object... params) {

		return null;
	}

	@Override
	protected void onPostExecute(JSONObject result) {
		if (pb.isShowing()) {
			pb.dismiss();
		}
		if (result != null) {
			try {
				String resultcode = result.getString("resultcode");
				if ("nonet".equals(resultcode)) {// 没有联网
					Utils.showToast(context.getApplicationContext(), "请检查网络");
					result = null;
				} else if ("404".equals(resultcode)) {// 网络不稳定
					Utils.showToast(context.getApplicationContext(), "网络不稳定!");
					result = null;
				}
			} catch (JSONException e) {
				result = null;
				e.printStackTrace();
			}
		} else {
			Utils.showToast(context.getApplicationContext(), "网络不稳定!");
		}
		super.onPostExecute(result);
	}

}
